package com.dzsw;

import com.dzsw.bean.WriteConfig;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

public class RewriteBinaryFile {

    private static final List<WriteConfig> CONFIG_LIST = Arrays.asList(
            new WriteConfig("tmp_0x6DF240L", 0x6DF240L, 9L, 18)
//            new WriteConfig("tmp_0x6DF330L", 0x6DF330L, 12L, 18),
//            new WriteConfig("tmp_0x6D2F0HL", 0x6DF2F0L, 16L, 18),
//            new WriteConfig("tmp_0x6DF240L", 0x6DF240L, 8L, 18),
//            new WriteConfig("tmp_0x6DF1E0L", 0x6DF1E0L, 4L, 18)
    );

    public static void main(String[] args) throws Exception {
        if (args.length != 3) {
            throw new RuntimeException("parameters error! need two parameters: fileFullPath and newName.");
        }
        writeFile(args[0], args[1], args[2]);
    }

    private static void writeFile(String filePath, String fileName, String targetName) throws Exception {
        // handle new name
        byte[] bytesTargetName = targetName.getBytes(StandardCharsets.UTF_16LE);
        // check file
        File originalFile = new File(filePath + File.separator + fileName);
        if (!originalFile.exists()) {
            throw new RuntimeException("File not found: " + originalFile.getAbsolutePath());
        }
        try (final RandomAccessFile raf = new RandomAccessFile(originalFile, "rw")) {
            for (WriteConfig conf : CONFIG_LIST) {
                // create temp file
                File tempFile = new File(filePath + File.separator + conf.getTempFileName());
                try (final RandomAccessFile tempRaf = new RandomAccessFile(tempFile, "rw")) {
                    // 记录原文件长度
                    long fileLength = raf.length();
                    // 如果插入位置超出文件长度，直接在末尾追加
                    if (conf.getStartPosition() > fileLength) {
                        raf.seek(fileLength);
                        raf.write(bytesTargetName);
                        return;
                    }
                    // 将插入点后的内容写入临时文件
                    raf.seek(conf.getEndPosition());
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = raf.read(buffer)) != -1) {
                        tempRaf.write(buffer, 0, bytesRead);
                    }
                    // 回到插入位置，写入新数据
                    raf.seek(conf.getStartPosition());
                    raf.write(bytesTargetName);
                    // 将临时文件中的内容写回原文件（接在新数据之后）
                    tempRaf.seek(0);
                    while ((bytesRead = tempRaf.read(buffer)) != -1) {
                        raf.write(buffer, 0, bytesRead);
                    }
                }
                tempFile.deleteOnExit();
            }
        }
    }
}
